import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'
import { encrypt,checkDigest,decrypt} from '@/utils/crypto'
import router from '@/router'
let ROOT;
let mode;//判断是否加密
if (process.env.NODE_ENV === 'development') {
  // ROOT = "/api"
  ROOT = window.ROOT
  mode=0
} else {
  ROOT = window.ROOT;
  mode=3
}
var service = axios.create({
  // baseURL: "http://139.196.106.25:8001/fmis-api/api", // url = base url + request url
  // baseURL: "http://127.0.0.1:8001/fmis", // url = base url + request url
  baseURL: ROOT,
  withCredentials: true,
  responseType:"blob",
  timeout: 20000 ,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    token:store.getters.token?getToken():null
  },
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    let ts=(new Date()).valueOf();//时间戳
    let token = getToken()
    if (token) {
      config.headers['token'] = token
    }
     console.log(config.data,'加密前参数')
    if(mode===3){
      config.data=encrypt(JSON.stringify(config.data));
    }else if(mode===0){
      let postData={
        msgId:'uid',
        token,
        mode:0,
        body:JSON.stringify(config.data),
        digest:null,
        ts
      }
      config.data=postData
    }
    // console.log(config.data,'加密后参数')
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
     return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  res => {
    console.log(res,'888')
    if(res.status!=200){
        this.$message.error('请求失败')
        return Promise.reject(new Error(res.message || 'Error')).catch(err => {
            // console.log(err) // 这里catch到错误
          })
    }
    return res

    
    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
   
  },
  error => {
     console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    // return Promise.reject(error)
  }
)

export default service
